package com.why.zing.admin.controller;


import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.why.zing.admin.util.UploadFileConfigUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * FastDFS 页面直接调用使用
 *
 * @author 睁眼看世界
 * @date 2019年12月29日
 */
@RestController
@RequestMapping("/image")
public class FastDFSFileController {


    @Value("${HOSTNAME}")
    private String hostName;


    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 上传图片
     */
    @PostMapping("/uploadImage")
    public String upload(@RequestParam(value = "file") MultipartFile multipart) throws Exception {
        String fileName = multipart.getOriginalFilename();
        InputStream inputStream = multipart.getInputStream();
        FastImageFile fastImageFile = UploadFileConfigUtil.crtFastImageFileOnly(inputStream, multipart.getSize(), FilenameUtils.getExtension(fileName));
        StorePath storePath = fastFileStorageClient.uploadImage(fastImageFile);
        return hostName + storePath.getFullPath();
    }

    /**
     * 下载文件
     */
    @PostMapping("/download")
    public void doDownload(HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String fileId = request.getParameter("fileId");
        String fileName = request.getParameter("fileName");
        if (StringUtils.isEmpty(fileName)) {
            throw new Exception("fileName is null");
        }
    }

    /**
     * 删除文件
     */
    @PostMapping("/delete")
    @ResponseBody
    public String delete(String filePath) throws Exception {
        fastFileStorageClient.deleteFile(filePath);
        return null;
    }

}
